package com.carleasoft.mps.core.jackson;

import com.carleasoft.mps.core.enums.BaseEnum;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 枚举反系列化规则自定义：支持客户端传参：枚举code 或 枚举name 或 枚举对象（取枚举对象的name）
 *
 * @author Alay
 * @date 2021-08-13 15:03
 * @project mps
 * @since
 */
@Component
public class BaseEnumDeserializer extends JsonDeserializer<BaseEnum> {

    @Override
    @SuppressWarnings("unchecked")
    public BaseEnum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String currentName = jp.currentName();
        Object currentValue = jp.getCurrentValue();
        @SuppressWarnings("rawtypes")
        Class enumClazz = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        BaseEnum valueOf;
        if (node instanceof IntNode) {
            // 当客户端传值为枚举的 code 的值得时候
            valueOf = (BaseEnum) BaseEnum.codeOf(enumClazz, node.asInt());
        } else if (node instanceof TextNode) {
            // 当客户端传值为 枚举的 name 时候
            valueOf = (BaseEnum) BaseEnum.sourceOf(enumClazz, node.asText());
        } else {
            // 客户端传参为枚举的对象
            valueOf = (BaseEnum) BaseEnum.sourceOf(enumClazz, node.get("name").asText());
        }
        return valueOf;
    }
}
